﻿using CastingWellEquipmentGUI.Config;
using CastingWellEquipmentGUI.Model;
using CastingWellEquipmentGUI.Utils;
using CastingWellEquipmentGUI.ViewModel.Common.Command;
using CastingWellEquipmentGUI.ViewModel.Common.WindowsManager;
using Confluent.Kafka;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;

namespace CastingWellEquipmentGUI.ViewModel.Pages
{
    public class CastWellPublicPageViewModel : ViewModelBase
    {
        #region 线程对象
        /// <summary>
        /// 动画线程
        /// </summary>
        private Thread animationThread = null;
        /// <summary>
        /// 更新数据线程
        /// </summary>
        private Thread tagInfoSyncThread = null;
        #endregion 线程对象
        #region 预检测项目
        private Visibility _PreDetectionVisibility;
        /// <summary>
        /// 预检测状态
        /// 注：控制预检测框显隐
        /// </summary>
        public Visibility PreDetectionVisibility
        {
            get { return _PreDetectionVisibility; }
            set { _PreDetectionVisibility = value; RaisePropertyChanged("PreDetectionVisibility"); }
        }
        /// <summary>
        /// 铸井排风机已运行
        /// </summary>
        public Brush Label_PreCheck1
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_PreCheck1") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// 铸井公辅电器柜温度正常
        /// </summary>
        public Brush Label_PreCheck2
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_PreCheck2") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }

        /// <summary>
        /// 紧急水阀测试正常
         #endregion 定义页面执行命令
        private const string showPageTitle = "CastWellPublicPage";
        /// <summary>
        /// 灯源切换命令
        /// </summary>
        public DelegateCommand SwitchLightCommand { get; set; }
        /// <summary>
        /// 风扇切换命令
        /// </summary>
        public DelegateCommand SwitchFanCommand { get; set; }

        private string _LightImageUrl;
        public string LightImageUrl
        {
            get { return _LightImageUrl; }
            set
            {
                _LightImageUrl = value;
                RaisePropertyChanged("LightImageUrl");
            }
        }
        private double _UpperFanAngle = 0;
        /// <summary>
        /// 上方轮盘旋转角度
        /// </summary>
        public double UpperFanAngle
        {
            get { return _UpperFanAngle; }
            set { _UpperFanAngle = value; RaisePropertyChanged("UpperFanAngle"); }
        }
        /// <summary>
        /// 构造方法
        /// </summary>
        public CastWellPublicPageViewModel()
        {
            SwitchLightCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(SwitchLightHandler)
            };
            SwitchFanCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(SwitchFanHandler)
            };
            //LightImageUrl = "/images/CastWellPublic/Light.png";
            // 消息通道注册
            initMessenger();
            // 初始化基础信息
            initBaseSet();
            //初始化线程
            initThread();
        }

        /// <summary>
        /// 初始化线程
        /// </summary>
        private void initThread()
        {
            // 动画线程
            animationThread = new Thread(animationThreadFunc);
            animationThread.SetApartmentState(ApartmentState.STA);
            animationThread.IsBackground = true;
            animationThread.Start();
            // 数据线程
            tagInfoSyncThread = new Thread(animationThreadFunc1);
            tagInfoSyncThread.SetApartmentState(ApartmentState.STA);
            tagInfoSyncThread.IsBackground = true;
            tagInfoSyncThread.Start();
        }
        /// <summary>
        /// 动画线程
        /// </summary>
        private void animationThreadFunc1()
        { // 创建消费者对象
            IConsumer<string, object> KafkaConsumer = KafkaHelper.GetConsumer();
            while (true)
            {
                if (SystemConfig.systemState == "预检测" || SystemConfig.systemState == "可见许可")
                {
                    PreDetectionVisibility = Visibility.Visible;
                }
                else
                {
                    PreDetectionVisibility = Visibility.Hidden;
                }
                // 网络中断不进行消费监听
                if (SystemConfig.SystemStatus == "网络中断")
                {
                    Thread.Sleep(1000);
                    continue;
                }
                if (ThreadController.RoundBarCastWellPublicThreadState)
                {
                    //开始消费
                    var result = KafkaConsumer.Consume();
                    if (result != null)
                    {
                        //手动提交
                        KafkaConsumer.Commit(result);
                        //获取消息内容
                        string tagId = result.Message.Value.ToString();
                        HashSet<Control> hashSet = KafkaHelper.UpdateCurrentUserTagValue(Int32.Parse(tagId), KafkaHelper.GetTagValueByKey(tagId.ToString()), showPageTitle);
                        if (hashSet != null && hashSet.Count > 0)
                        {
                            DoChanged(hashSet);
                        }
                    }
                }

                Thread.Sleep(10);
            }
        }
        /// <summary>
        /// 动画线程
        /// </summary>
        private void animationThreadFunc()
        {
            while (true)
            {
                if (ThreadController.RoundBarCastWellPublicThreadState)
                {

                    // 送丝机正转与反转动画控制

                    if (UpperFanAngle < 360)
                    {
                        UpperFanAngle += 1;
                    }
                    else
                    {
                        UpperFanAngle = 0;
                        UpperFanAngle += 1;
                    }
                }
                Thread.Sleep(10);
            }
        }
        /// <summary>
        /// 初始化基础信息
        /// </summary>
        private void initBaseSet()
        {
            // 页面初始化
            HashSet<Control> tempHashSet = SysCommon.getCurrentControl(showPageTitle);
            if (tempHashSet.Count > 0)
            {
                DoChanged(tempHashSet);
            }
            ///** 设定值初始化 **/
            //_Button_PulsesNum = TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Button_PulsesNum");
            //RaisePropertyChanged("Button_PulsesNum");

        }
        /// <summary>
        /// 消息通道注册
        /// ViewModel之间数据通信使用，整个项目全局唯一
        /// </summary>
        private void initMessenger()
        {
            //灯触发
            Messenger.Default.Register<string>(this, showPageTitle + "Button_Light", (message) =>
            {
                setLightOnOrOff(message.ToString());
            });
            //风扇触发
            Messenger.Default.Register<string>(this, showPageTitle + "Button_Fan", (message) =>
            {
                setFanOnOrOff(message.ToString());
            });
            //页面切换执行控件刷新
            Messenger.Default.Register<string>(this, showPageTitle + "_DoChange", (message) =>
            {
                HashSet<Control> tempHashSet = SysCommon.getCurrentControl(showPageTitle);
                if (tempHashSet.Count > 0)
                {
                    DoChanged(tempHashSet);
                }
            });
        }
        /// <summary>
        /// 灯开启或关闭
        /// </summary>
        /// <param name="message"></param>
        private void setLightOnOrOff(string message)
        {
            if (message == "" || message == null)
            {
                return;
            }
            if (message == "True")
            {
                if (KafkaHelper.SendGatewayChangeTagMessage(showPageTitle, "Button_Light", "true"))
                {
                    LightImageUrl = "/images/CastWellPublic/Light.png";
                }
            }
            else if (message == "False")
            {
                if (KafkaHelper.SendGatewayChangeTagMessage(showPageTitle, "Button_Light_up", "true"))
                {
                    LightImageUrl = "/images/CastWellPublic/OffLight.png";
                }
            }
        }
        /// <summary>
        /// 风扇开启或关闭
        /// </summary>
        /// <param name="message"></param>
        private void setFanOnOrOff(string message)
        {
            if (message == "" || message == null)
            {
                return;
            }
            if (message == "True")
            {
                if (KafkaHelper.SendGatewayChangeTagMessage(showPageTitle, "Button_Fan", "true"))
                {
                    ThreadController.RoundBarCastWellPublicThreadState = true;
                }
            }
            else if (message == "False")
            {
                if (KafkaHelper.SendGatewayChangeTagMessage(showPageTitle, "Button_Fan_up", "true"))
                {
                    ThreadController.RoundBarCastWellPublicThreadState = false;
                }
            }
        }

        /// <summary>
        /// 执行动作
        /// </summary>
        /// <param name="hashSet"></param>
        private void DoChanged(HashSet<Control> hashSet)
        {
            //遍历返回的控件信息刷新对应的控件
            foreach (Control item in hashSet)
            {
                switch (item.ControlName)
                {
                    /** 灯开启 **/
                    case "Button_Light":
                        if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, item.ControlName) == "true")
                        {
                            LightImageUrl = "/images/CastWellPublic/Light.png";
                        }
                        break;
                    /** 灯关闭 **/
                    case "Button_Light_up":
                        if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, item.ControlName) == "true")
                        {
                            LightImageUrl = "/images/CastWellPublic/OffLight.png";
                        }
                        break;
                    /** 风扇启动 **/
                    case "Button_Fan":
                        if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, item.ControlName) == "true")
                        {
                            ThreadController.RoundBarCastWellPublicThreadState = true;
                        }
                        break;
                    /** 风扇关闭 **/
                    case "Button_Fan_up":
                        if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, item.ControlName) == "true")
                        {
                            ThreadController.RoundBarCastWellPublicThreadState = false;
                        }
                        break;
                    default:
                        /** 刷新页面值变化信息 **/
                        RaisePropertyChanged(item.ControlName);
                        break;
                }
            }
        }
        /// <summary>
        /// 切换命令方法
        /// </summary>
        /// <param name="obj"></param>
        private void SwitchLightHandler(object obj)
        {
            // 获取参数，此处参数为按钮名称
            string param = obj.ToString();
            WindowManager.ShowModalOnOrOffPanel("OnOrOffPanel", showPageTitle + param);
            //WindowManager.ShowModalOnOrOffPanel("OnOrOffPanel", "CastWellPublicPage");
            //if (LightImageUrl == "/images/CastWellPublic/Light.png")
            //{
            //    LightImageUrl = "/images/CastWellPublic/OffLight.png";
            //}
            //else {
            //    LightImageUrl = "/images/CastWellPublic/Light.png";
            //}
        }

        private void SwitchFanHandler(object obj)
        {
            // 获取参数，此处参数为按钮名称
            string param = obj.ToString();
            WindowManager.ShowModalOnOrOffPanel("OnOrOffPanel", showPageTitle + param);
        }
    }
}
